﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

using Fusion;
using Fusion.Interface;

namespace Fusion
{
    public class Button : Control
    {
        #region Fields

		Image image;
		public Rectangle srcRect;
		public Rectangle hoverRect;
		public Rectangle pressRect;

        #endregion

        #region Constructors

        // Creates a button centered at origin, sized by size
		public Button( Vector2 center, Vector2 Size, string texture, Rectangle src, VoidDelegate clickEvent, VoidDelegate releaseEvent )
		{
			position = center;
			size = Size;

			image = new Image( texture );
			srcRect = src;
			hoverRect = src;
			pressRect = src;

			Clicked += clickEvent;
			Released += releaseEvent;
		}
        public Button( Vector2 center, Vector2 Size, string texture, Rectangle src, Rectangle press, VoidDelegate clickEvent, VoidDelegate releaseEvent )
		{
			position = center;
			size = Size;

			image = new Image( texture );
			srcRect = src;
			hoverRect = src;
			pressRect = press;

            Clicked += clickEvent;
            Released += releaseEvent;
        }

        #endregion

        #region Methods

		// Checks input, changes state, fires events, and updates graphics
		public void Control( Vector2 cursor, bool button )
		{
			Vector2 projection = new Vector2();

			// Checks cursor info
			if( Intersect( cursor, ref projection ) == true )
				hovered = true;
			else
				hovered = false;

			// Cursor is not pressed
			if( button == false )
			{
				// Raise release event if appropriate
				if( pressed == true )
					if( Released != null )
						Released();
				pressed = false;
			}
			// Cursor is pressed, and button is hovered
			else if( hovered )
			{
				if( pressed == false )
				{
					if( Clicked != null )
						Clicked();

					pressed = true;
				}
			}

		}

		/// <summary> Update method </summary>
		public override void Update()
		{
			float step = Engine.period * 4;

			base.Update();
		}

        /// <summary> Renders the button </summary>
        public override void Draw()
		{
			if( hidden == true )
				return;

			base.Draw();
			Rectangle dest = new Rectangle( (int)( Position.X ), (int)( Position.Y ), (int)Size.X, (int)Size.Y );
			 if( pressed )
				 Engine.spriteBatch.Draw( image.Texture, dest, pressRect, Color.White );
			else if( hovered )
				 Engine.spriteBatch.Draw( image.Texture, dest, hoverRect, Color.White );
			else
				 Engine.spriteBatch.Draw( image.Texture, dest, srcRect, Color.White );
        }

        #endregion
    }
}
